package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.DeleteSetmealException;
import com.itheima.dao.SetmealMapper;
import com.itheima.dto.SetmealDto;
import com.itheima.pojo.Setmeal;
import com.itheima.pojo.SetmealDish;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * @author Gareth Cao
 * @date 2022/4/28 16:16
 */
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 同时操作多张数据表,需要进行事务管理
     *
     * @param setmealDto
     */
    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        //新增套餐
        this.save(setmealDto);
        //获取setmealDto中setmealDishes集合
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        //setmealDishes中缺乏setmeal_id数据
        setmealDishes.forEach(setmealDish -> setmealDish.setSetmealId(setmealDto.getId()));
        setmealDishService.saveBatch(setmealDishes);
    }

    /**
     * 批量删除
     *
     * @param ids
     */
    @Override
    @Transactional
    public void removeWithDish(Long[] ids) {
        //判断要删除的套餐是否启售 sql语句:delete from setmeal where id in ids and status = 1
        QueryWrapper<Setmeal> queryWrapper = new QueryWrapper<>();
        //ids.length > 0为true,sql语句才拼接条件
        queryWrapper.in(ids.length > 0, "id", Arrays.asList(ids));
        queryWrapper.eq("status", 1);
        if (this.count(queryWrapper) > 0) {
            throw new DeleteSetmealException("套餐启售中,无法删除");
        }

        //先删除套餐表数据
        this.removeByIds(Arrays.asList(ids));
        //再删除setmeal_dish中的数据
        QueryWrapper<SetmealDish> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.in("setmeal_id", Arrays.asList(ids));
        setmealDishService.remove(queryWrapper1);
    }
}
